package com.cxmx.escort.config.sdk;

import com.huawei.iotplatform.client.NorthApiClient;
import com.huawei.iotplatform.client.NorthApiException;
import com.huawei.iotplatform.client.dto.SubDeviceDataInDTO;
import com.huawei.iotplatform.client.dto.SubscriptionDTO;
import com.huawei.iotplatform.client.invokeapi.Authentication;
import com.huawei.iotplatform.client.invokeapi.SubscriptionManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class NBIoTAuthService {

    private static  byte[] lock = new byte[0];

    @Autowired
    NBIoTService nbIoTService;

    @Value("${nb.oceanconnect.callback}")
    private String callbackAddress;

    @PostConstruct
    private void postConstruct() {
        login();
        subscriptionEvent("deviceDataChanged");
        subscriptionEvent("commandRsp");

    }

    public void login() {
        try {
            NorthApiClient northApiClient = nbIoTService.getNorthApiClient();
            Authentication auth = new Authentication(northApiClient);
            auth.startRefreshTokenTimer();
        } catch (NorthApiException northApiException) {
            northApiException.printStackTrace();
        }
    }
    public void stop(){
        try {
            NorthApiClient northApiClient = nbIoTService.getNorthApiClient();
            Authentication auth = new Authentication(northApiClient);
            auth.stopRefreshTokenTimer();
        }catch (NorthApiException northApiException){
            northApiException.printStackTrace();
        }
    }



    public void subscriptionEvent(String notifyType){

        try {
            SubscriptionManagement subscriptionManagement = new SubscriptionManagement(nbIoTService.getNorthApiClient());
            SubDeviceDataInDTO sddInDTO = new SubDeviceDataInDTO();
            sddInDTO.setNotifyType(notifyType);
            sddInDTO.setCallbackUrl(callbackAddress);

            SubscriptionDTO subDTO = subscriptionManagement.subDeviceData(sddInDTO, null, null);
        } catch (NorthApiException e) {
        }
    }

    @PreDestroy
    public void preDestroy() {
        stop();
    }
}
